<template>
	<section>
		<ul class="mt20 fontc0">
			<li class="line tl lh25">
				<span
					class="red dbi fs14 ml10"
				>账户余额: {{gold?userInfo.scoreUsable:userInfo.moneyUsable|formatMoney()}}</span>
			</li>
			<li class="clearfix line">
				<strong class="fl">买卖方向</strong>
				<div class="fl clearfix">
					<span class="fl big-box" :class="{active:this.direction=='up'}" @click="direction='up'">
						买涨
						{{this.curQuota.askPrice?this.curQuota.askPrice:0|formatPoint(this.marketPoint)}}
					</span>
					<span
						class="fl big-box ml5"
						:class="{active:this.direction=='down'}"
						@click="direction='down'"
					>
						买跌
						{{this.curQuota.bidPrice?this.curQuota.bidPrice:0|formatPoint(this.marketPoint)}}
					</span>
				</div>
			</li>
			<li class="clearfix line flex">
				<strong class="fl">交易手数</strong>
				<div class="fl flex1">
					<em class="fl cube" :class="{active:curHand>minHand}" @click="subCurHand">
						<span class="iconfont icon-minus"></span>
					</em>
					<input class="fl" v-model="filterCurHand" type="number">
					<em class="fl cube" :class="{active:curHand<maxHand}" @click="addCurHand">
						<span class="iconfont icon-plus"></span>
					</em>
				</div>
			</li>
			<li class="clearfix flex line">
				<strong class="fl">保证金(￥)</strong>
				<div class="flex1">
					<span
						class="fl box mr5"
						:key="idx"
						:class="{active:item==getHighPeiZi.assets[curAssetsIdx].marginBeat}"
						v-for="(item,idx) in marginBeat"
						v-show="idx>2?!foldMarginBeat:true"
						@click="setCurAssetsIdx(idx)"
					>{{item*curHand*getHighPeiZi.ratio|formatMoney()}}</span>
					<span
						class="fl arrow-box mr5 iconfont"
						:class="foldMarginBeat?'icon-zhankaixia':'icon-shouqishang'"
						@click="foldMarginBeat=!foldMarginBeat"
					></span>
				</div>
			</li>

			<li class="clearfix line flex">
				<strong class="fl">止损价</strong>
				<div class="fl flex1">
					<em
						class="fl cube iconfont icon-minus fs10"
						:class="{active:this.stopLossBeatClickL}"
						@click="this.subCurStopLossBeat"
					></em>
					<input class="fl" v-model="this.stopLossBeatPrice" type="number">
					<em
						class="fl cube iconfont icon-plus fs10"
						:class="{active:this.stopLossBeatClickR}"
						@click="this.addCurStopLossBeat"
					></em>
					<span
						class="fl ml5"
					>{{stopLossBeatText}}￥{{this.stopLossBeatMoney*getHighPeiZi.ratio|formatMoney()}}</span>
				</div>
			</li>

			<li class="clearfix line flex">
				<strong class="fl">止盈价</strong>
				<div class="fl flex1">
					<em
						class="fl cube iconfont icon-minus fs10"
						:class="{active:this.stopWinBeatClickL}"
						@click="this.subCurStopWinBeat"
					></em>
					<input class="fl" v-model="this.stopWinBeatPrice" type="number">
					<em
						class="fl cube iconfont icon-plus fs10"
						:class="{active:this.stopWinBeatClickR}"
						@click="this.addCurStopWinBeat"
					></em>
					<span class="fl ml5">{{stopWinBeatText}} ￥{{stopWinBeatMoney*getHighPeiZi.ratio|formatMoney()}}</span>
				</div>
			</li>

			<li class="clearfix fee">
				<strong class="fl">合计支付</strong>
				<div class="fl clearfix">
					<span class="fl">￥{{(marginBeatMoney+fee*curHand)*getHighPeiZi.ratio|formatMoney()}}</span>
					<span
						class="iconfont tc ml10 fl"
						:class="foldText?'icon-zhankaixia':'icon-shouqishang'"
						@click="foldText=!foldText"
					></span>
				</div>
			</li>
			<li class="clearfix fee" v-show="!foldText">
				<strong class="fl">触发保证金</strong>
				<div class="fl clearfix">
					<span class="fl">￥{{marginBeatMoney*getHighPeiZi.ratio|formatMoney()}}</span>
				</div>
			</li>
			<li class="clearfix fee" v-show="!foldText">
				<strong class="fl">交易综合费</strong>
				<div class="fl clearfix">
					<span class="fl">￥{{fee*getHighPeiZi.ratio*curHand|formatMoney()}}</span>
				</div>
			</li>
		</ul>
		<div class="buy-button pl10 pr10 mt10">
			<p
				class="lh40 fs16"
				@click="submitOrder"
				:class="{bgred:direction=='up',bggreen:direction=='down'}"
			>
				{{direction=='up'?'买涨 ':'买跌 '}}
				{{direction=='up'?this.curQuota.askPrice:this.curQuota.bidPrice|formatPoint(this.marketPoint)}}
			</p>
		</div>
	</section>
</template>
<script>
import { MessageBox, Toast, Indicator } from 'mint-ui'

import accounting from 'accounting'
import { orderNewOrderSubmitNewOrder } from '@api/order.js'

//account的配置更改
accounting.settings = {
	currency: {
		symbol: '', // default currency symbol is '$'
		format: '%s%v', // controls output: %s = symbol, %v = value/number (can be object: see below)
		decimal: '.', // decimal point separator
		thousand: ',', // thousands separator
		precision: 2 // decimal places
	},
	number: {
		precision: 0, // default precision on numbers is 0
		thousand: ',',
		decimal: '.'
	}
}

import { mapState, mapGetters, mapMutations } from 'vuex'
export default {
	name: 'High',
	data() {
		return {
			direction: 'up',
			curAssetsIdx: 1,
			curHand: 0,

			curStopLossBeat: 0,
			curStopWinBeat: 0,
			//能否下单
			orderKey: true,

			// 折叠内容
			foldText: true,
			foldMarginBeat: true
		}
	},

	computed: {
		...mapState(['curQuota', 'gold', 'userInfo','topupAuth', 'curVariety', 'buyDirection']),
		...mapGetters(['getHighPeiZi']),
		marketPoint() {
			if (this.getHighPeiZi) {
				return this.getHighPeiZi.marketPoint
			} else {
				return 0
			}
		},
		minHand() {
			if (this.getHighPeiZi && this.getHighPeiZi.assets) {
				return this.getHighPeiZi.assets[this.curAssetsIdx].minHands
			} else {
				return 0
			}
		},
		maxHand() {
			if (this.getHighPeiZi && this.getHighPeiZi.assets) {
				return this.getHighPeiZi.assets[this.curAssetsIdx].maxHands
			} else {
				return 0
			}
		},
		filterCurHand: {
			get() {
				return this.curHand
			},
			set(hand) {
				if (hand) {
					hand = parseFloat(hand)
				} else {
					hand = 0
				}
				this.curHand = hand
			}
		},
		minStopWinBeat() {
			if (this.getHighPeiZi && this.getHighPeiZi.assets) {
				return this.getHighPeiZi.assets[this.curAssetsIdx].stopWinBeat[0]
			} else {
				return 0
			}
		},
		maxStopWinBeat() {
			if (this.getHighPeiZi && this.getHighPeiZi.assets) {
				const length = this.getHighPeiZi.assets[this.curAssetsIdx].stopWinBeat.length
				return this.getHighPeiZi.assets[this.curAssetsIdx].stopWinBeat[length - 1]
			} else {
				return 0
			}
		},
		marginBeat() {
			if (this.getHighPeiZi && this.getHighPeiZi.assets) {
				return this.getHighPeiZi.assets.map((value, idx, arr) => {
					return value.marginBeat
				})
			} else {
				return 0
			}
		},

		stepMoney() {
			if (this.getHighPeiZi) {
				return this.getHighPeiZi.beatFewPoints * this.getHighPeiZi.eachPointMoney
			} else {
				return 0
			}
		},
		stopLossBeat() {
			if (this.getHighPeiZi && this.getHighPeiZi.assets) {
				return this.getHighPeiZi.assets[this.curAssetsIdx].stopLossBeat
			} else {
				return 0
			}
		},
		stopLossBeatPrice() {
			if (this.getHighPeiZi) {
				if (this.direction == 'up') {
					return (this.curQuota.askPrice - (this.curStopLossBeat / this.stepMoney) * this.getHighPeiZi.beatFewPoints).toFixed(this.marketPoint)
				}
				if (this.direction == 'down') {
					return (this.curQuota.bidPrice + (this.curStopLossBeat / this.stepMoney) * this.getHighPeiZi.beatFewPoints).toFixed(this.marketPoint)
				}
			} else {
				return 0
			}
		},
		stopWinBeatPrice() {
			if (this.getHighPeiZi) {
				if (this.direction == 'up') {
					return (this.curQuota.askPrice + (this.curStopWinBeat / this.stepMoney) * this.getHighPeiZi.beatFewPoints).toFixed(this.marketPoint)
				}
				if (this.direction == 'down') {
					return (this.curQuota.bidPrice - (this.curStopWinBeat / this.stepMoney) * this.getHighPeiZi.beatFewPoints).toFixed(this.marketPoint)
				}
			} else {
				return 0
			}
		},
		// 处理止损左右是否能点击
		stopLossBeatClickL() {
			if (this.getHighPeiZi) {
				if (this.direction == 'up') {
					if (this.stopLossBeat - this.curStopLossBeat >= this.stepMoney) {
						return true
					} else {
						return false
					}
				}
				if (this.direction == 'down') {
					if (this.curStopLossBeat > this.stepMoney) {
						return true
					} else {
						return false
					}
				}
			} else {
				return false
			}
		},
		stopLossBeatClickR() {
			if (this.direction == 'up') {
				if (this.curStopLossBeat > this.stepMoney) {
					return true
				} else {
					return false
				}
			}
			if (this.direction == 'down') {
				if (this.stopLossBeat - this.curStopLossBeat >= this.stepMoney) {
					return true
				} else {
					return false
				}
			}
		},
		// 处理止盈左右是否能点击
		stopWinBeatClickL() {
			if (this.getHighPeiZi) {
				if (this.direction == 'up') {
					if (this.curStopWinBeat > this.minStopWinBeat) {
						return true
					} else {
						return false
					}
				}
				if (this.direction == 'down') {
					if (this.curStopWinBeat < this.maxStopWinBeat) {
						return true
					} else {
						return false
					}
				}
			} else {
				return false
			}
		},
		stopWinBeatClickR() {
			if (this.getHighPeiZi) {
				if (this.direction == 'up') {
					if (this.curStopWinBeat >= this.maxStopWinBeat) {
						return false
					} else {
						return true
					}
				}
				if (this.direction == 'down') {
					if (this.curStopWinBeat > this.minStopWinBeat) {
						return true
					} else {
						return false
					}
				}
			} else {
				return false
			}
		},
		//计算保证金
		marginBeatMoney() {
			if (this.getHighPeiZi && this.getHighPeiZi.assets) {
				return this.getHighPeiZi.assets[this.curAssetsIdx].marginBeat * this.curHand
			} else {
				return 0
			}
		},
		//计算止损金文字
		stopLossBeatText() {
			// ≥
			var symbol
			if (this.direction == 'up') {
				symbol = '≤ '
			}
			if (this.direction == 'down') {
				symbol = '≥ '
			}
			return symbol + this.stopLossBeatPrice + ' 预计亏损'
		},
		//计算止损金
		stopLossBeatMoney() {
			if (this.getHighPeiZi && this.getHighPeiZi.sign) {
				return this.curStopLossBeat * this.curHand
			} else {
				return '···'
			}
		},
		//计算止盈金文字
		stopWinBeatText() {
			// ≥
			var symbol
			if (this.direction == 'up') {
				symbol = '≥ '
			}
			if (this.direction == 'down') {
				symbol = '≤ '
			}
			return symbol + this.stopWinBeatPrice + ' 预计盈利'
		},
		//计算止盈金钱
		stopWinBeatMoney() {
			if (this.getHighPeiZi && this.getHighPeiZi.sign) {
				return this.curStopWinBeat * this.curHand
			} else {
				return '···'
			}
		},
		fee() {
			if (this.getHighPeiZi) {
				return this.getHighPeiZi.fees
			} else {
				return '···'
			}
		}
	},
	methods: {
		...mapMutations(['setToOrder', 'setOrderType']),

		initHighCart() {
			this.curContractsCode = ''
			this.direction = 'up'
			this.curAssetsIdx = 1
			this.curHand = 0
			this.curStopLossBeat = 0
			this.curStopWinBeat = 0
		},
		subCurHand() {
			if (this.curHand > this.minHand) {
				this.curHand = (+this.curHand - 0.1).toFixed(1)

				this.curHand = +this.curHand
			}
		},
		addCurHand() {
			if (this.curHand < this.maxHand) {
				this.curHand = (+this.curHand + 0.1).toFixed(1)
				this.curHand = +this.curHand
			}
		},
		setCurAssetsIdx(idx) {
			//设置idx;
			this.curAssetsIdx = idx
			//重新计算当前止损止盈
			this.curStopLossBeat = this.getHighPeiZi.assets[this.curAssetsIdx].stopLossBeat

			const defaultIdx = +this.getHighPeiZi.assets[this.curAssetsIdx].isdefault
			this.curStopWinBeat = this.getHighPeiZi.assets[this.curAssetsIdx].stopWinBeat[defaultIdx]
		},
		subCurStopLossBeat() {
			if (this.direction == 'up') {
				if (this.curStopLossBeat >= this.stopLossBeat) {
					return
				}
				this.curStopLossBeat += this.stepMoney
			}
			if (this.direction == 'down') {
				if (this.curStopLossBeat <= this.stepMoney) {
					return
				}
				this.curStopLossBeat -= this.stepMoney
			}
		},
		addCurStopLossBeat() {
			if (this.direction == 'up') {
				if (this.curStopLossBeat <= this.stepMoney) {
					return
				}
				this.curStopLossBeat -= this.stepMoney
			}
			if (this.direction == 'down') {
				if (this.curStopLossBeat >= this.stopLossBeat) {
					return
				}
				this.curStopLossBeat += this.stepMoney
			}
		},
		subCurStopWinBeat() {
			if (this.direction == 'up') {
				if (this.curStopWinBeat <= this.minStopWinBeat) {
					return
				}
				this.curStopWinBeat -= this.stepMoney
			}
			if (this.direction == 'down') {
				if (this.curStopWinBeat >= this.maxStopWinBeat) {
					return
				}
				this.curStopWinBeat += this.stepMoney
			}
		},
		addCurStopWinBeat() {
			if (this.direction == 'up') {
				if (this.curStopWinBeat >= this.maxStopWinBeat) {
					return
				}
				this.curStopWinBeat += this.stepMoney
			}
			if (this.direction == 'down') {
				if (this.curStopWinBeat <= this.minStopWinBeat) {
					return
				}
				this.curStopWinBeat -= this.stepMoney
			}
		},
		initHighCart() {
			this.curContractsCode = ''
			this.direction = 'up'
			this.curAssetsIdx = 1
			this.curHand = 0
			this.curStopLossBeat = 0
			this.curStopWinBeat = 0
			this.orderKey = true
		},
		submitOrder() {
			if (!this.curHand) {
				MessageBox('高级模式', '手数不正确')
				return
			}
			if (+this.curHand < this.minHand || +this.curHand > this.maxHand) {
				MessageBox('高级模式', '请输入' + this.minHand + '~' + this.maxHand + '内的交易手数')
				return
			}
			if (!this.orderKey) return
			Indicator.open({
				text: '提交订单中...',
				spinnerType: 'fading-circle'
			})
			if (this.direction == 'up') {
				var direction = 1
				var price = this.curQuota.bidPrice
			} else if (this.direction == 'down') {
				var direction = 0
				var price = this.curQuota.askPrice
			} else {
				alert('direction 出错')
				return
			}

			const params = {
				handsNum: +this.curHand,
				payType: this.gold ? 0 : 1,
				varietyId: this.curVariety.varietyId,
				assetsId: this.getHighPeiZi.assets[this.curAssetsIdx].assetsId,
				direction: direction,
				stopLossPrice: Math.round(this.curStopLossBeat * this.curHand), //四舍五入取整
				stopWinPrice: Math.round(this.curStopWinBeat * this.curHand),
				orderMode: 2
			}
			this.orderKey = false
			orderNewOrderSubmitNewOrder(params)
				.then(res => {
					Indicator.close()
					if (res.code == 200) {
						if (params.payType === 1) {
							_hmt.push([
								'_trackOrder',
								{
									orderId: new Date().toString(),
									orderTotal: +(this.marginBeatMoney + this.fee * this.curHand) * this.getHighPeiZi.ratio,
									skuId: window.userPhone,
									skuName: '高级,' + new Date().toString(),
									category: this.curVariety.varietyName,
									Quantity: params.handsNum,
									item: [
										{
											skuId: window.userPhone,
											skuName: '高级,' + new Date().toString(),
											category: this.curVariety.varietyName,
											Price: (+(this.marginBeatMoney + this.fee * this.curHand) * this.getHighPeiZi.ratio) / params.handsNum,
											Quantity: params.handsNum
										}
									]
								}
							])
						}

						this.$store.dispatch('getUserInfo')
						MessageBox.confirm('', {
							title: '高级模式',
							message: '下单成功，是否查看?',
							confirmButtonText: '查看',
							confirmButtonClass: 'red'
						}).then(action => {
							this.$store.commit('setToOrder', true) //chart 会watch 这个值，如果变为true就会跳转
							this.$store.commit('setOrderType', '1') //order 取这个值，显示持仓或挂单
						})
					} else {
                        if (res.msg === '下单失败,失败原因:余额不足' && params.payType === 1) {
                            MessageBox.confirm(' ', {
                                title: '高级模式',
                                message: '实盘账户余额不足，请立即充值',
                                confirmButtonText: '去充值',
                                confirmButtonClass: 'red'
                            }).then(action => {
                                if (action === 'confirm') {
                                    this.getTopupAuth()
                                }
                            })
                        } else {
						    MessageBox('挂单模式', res.msg)
                        }
                    }
                    
                    Indicator.close()
					this.orderKey = true
				}).catch((err) => {
                    console.log('err-->' ,err)
                    this.orderKey = true
                    Indicator.close()
					MessageBox('高级模式', err.msg)
				})
        },
        getTopupAuth() {
            if (Object.keys(this.topupAuth).length === 0) {
                this.$router.push({
                    path: "/login",
                });
            } else if (this.topupAuth.identify === 1 && !this.topupAuth.cardState) {
                MessageBox.confirm("", {
                    title: "充值",
                    message: "为了您的资金安全，请前去绑卡",
                    confirmButtonText: "去绑定",
                    confirmButtonClass: "red"
                }).then(() => {
                    this.$router.push({
                        path: "/account/bindbank",
                    });
                });
            } else {
                window.location.href = "./account/paySelect.html";
            }
        }
	},
	//监控配资的变化;
	watch: {
		getHighPeiZi(newer, older) {
			this.initHighCart()
			//初始化手数为最小手
			// this.curHand = +newer.assets  [this.curAssetsIdx].minHands;
			this.curHand = +newer.assets[this.curAssetsIdx].isdefault || 1
			//设置当前价格
			this.curStopLossBeat = newer.assets[this.curAssetsIdx].stopLossBeat
			const defaultIdx = +this.getHighPeiZi.assets[this.curAssetsIdx].isdefault
			this.curStopWinBeat = newer.assets[this.curAssetsIdx].stopWinBeat[defaultIdx]
		},
		buyDirection(newer, older) {
			if (newer === 1) {
				this.direction = 'up'
			}
			if (newer === 0) {
				this.direction = 'down'
			}
		}
	},
	filters: {
		formatMoney(money) {
			return accounting.formatMoney(money)
		},
		formatPoint(price, point) {
			if (price && point) {
				return price.toFixed(point)
			} else {
				return price
			}
		}
	}
}
</script>
<style scoped lang='scss'>
strong {
	width: rem(80px);
	text-align: left;
	font-size: rem(13px);
	margin-left: rem(10px);
}

.box {
	color: #666;
	min-width: rem(30px);
	padding-left: rem(5px);
	padding-right: rem(5px);
	width: auto;
	box-sizing: border-box;
	border-radius: rem(2px);
	border: 1px solid #aaaaaa;
}

.fix {
	min-width: rem(50px);
}

.arrow-box {
	border: 1px solid #aaa;
	border-radius: rem(2px);
	width: rem(30px);
	line-height: rem(28px);
	height: rem(28px);
	box-sizing: border-box;
	color: #707284;
}

.line {
	border-bottom: 1px solid #f2f2f2;
}

.big-box {
	width: rem(90px);
	box-sizing: border-box;
	border-radius: rem(2px);
	border: 1px solid #aaaaaa;
	color: #666;
}

.cube,
span,
input,
strong {
	height: rem(28px);
	line-height: rem(28px);
	margin-top: rem(5px);
	margin-bottom: rem(5px);
}

.cube {
	width: rem(28px);
	border: 1px solid #aaa;
	box-sizing: border-box;
	border-radius: rem(2px);
}

input {
	width: rem(70px);
	border: 0 none;
	outline: 0 none;
	text-align: center;
	background-color: transparent;
	color: #2e2d2d;
}

.buy-button p {
	border: 0 none;
	width: 100%;
	padding-bottom: 0;
	border-radius: rem(4px);
	color: #fff;
}

.active {
	color: #fff;
	background-color: #ef9d2e;
	border-color: #ef9d2e;
}

.text {
	/* text-indent: 80px; */
	color: #666;
}

.flex {
	display: flex;
}

.flex1 {
	flex: 1;
}

.fee strong {
	font-size: rem(13px);
	white-space: nowrap;
	margin-top: 0;
	margin-bottom: 0;
}

.fee span {
	font-size: rem(13px);
	margin-top: 0;
	margin-bottom: 0;
}
input {
	font-size: rem(13px);
}
</style>